package com.bookcloud.java21.aitools.aie05;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;

/** Main Frame with tabbed interface 主界面，包含选项卡式界面用于切换不同功能 */
public class MainFrame extends JFrame {

  private JTabbedPane tabbedPane;
  private TodaySignUI todaySignUI;
  private HistorySignUI historySignUI;
  private SignStaticsReportUI signStaticsReportUI;

  public MainFrame() {
    initializeFrame();
    createComponents();
    setupLayout();
    setupEventHandlers();
  }

  /** Initialize the main frame 初始化主窗口 */
  private void initializeFrame() {
    setTitle("学生签到管理系统");
    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    setSize(1000, 700);
    setLocationRelativeTo(null); // Center the window

    // Set the application icon (you can add an icon file later)
    try {
      // setIconImage(Toolkit.getDefaultToolkit().getImage("icon.png"));
    } catch (Exception e) {
      // Icon not found, continue without it
    }

    // Set Look and Feel
    try {
      // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /** Create the main components 创建主要组件 */
  private void createComponents() {
    // Create tabbed pane
    tabbedPane = new JTabbedPane();
    tabbedPane.setFont(new Font("微软雅黑", Font.PLAIN, 14));
    tabbedPane.setBackground(Color.WHITE);

    // Create Today's Sign-in UI
    todaySignUI = new TodaySignUI();

    // Create History Sign-in UI
    historySignUI = new HistorySignUI();

    // Create Statistics Report UI
    signStaticsReportUI = new SignStaticsReportUI();

    // Add tabs
    tabbedPane.addTab("今日签到", createTabIcon("📝"), todaySignUI, "今日学生签到管理");
    tabbedPane.addTab("查看历史签到", createTabIcon("📆"), historySignUI, "查看历史签到记录");
    tabbedPane.addTab("统计", createTabIcon("📈"), signStaticsReportUI, "签到统计报表");

    // Set the default selected tab
    tabbedPane.setSelectedIndex(0);
  }

  /** Setup the layout 设置布局 */
  private void setupLayout() {
    setLayout(new BorderLayout());

    // Create menu bar
    JMenuBar menuBar = createMenuBar();
    setJMenuBar(menuBar);

    // Create status bar
    JPanel statusBar = createStatusBar();

    // Add components
    add(tabbedPane, BorderLayout.CENTER);
    add(statusBar, BorderLayout.SOUTH);
  }

  /** Setup event handlers 设置事件处理器 */
  private void setupEventHandlers() {
    // Window close event
    addWindowListener(
        new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
            int option =
                JOptionPane.showConfirmDialog(
                    MainFrame.this,
                    "确定要退出系统吗？",
                    "退出确认",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);

            if (option == JOptionPane.YES_OPTION) {
              System.exit(0);
            }
          }
        });

    // Tab selection event
    tabbedPane.addChangeListener(
        e -> {
          int selectedIndex = tabbedPane.getSelectedIndex();
          String tabTitle = tabbedPane.getTitleAt(selectedIndex);
          updateStatusBar("当前页面: " + tabTitle);
        });
  }

  /** Create menu bar 创建菜单栏 */
  private JMenuBar createMenuBar() {
    JMenuBar menuBar = new JMenuBar();
    menuBar.setBackground(Color.WHITE);

    // File menu
    JMenu fileMenu = new JMenu("文件(F)");
    fileMenu.setMnemonic('F');
    fileMenu.setFont(new Font("微软雅黑", Font.PLAIN, 12));

    JMenuItem exportItem = new JMenuItem("导出数据(E)");
    exportItem.setMnemonic('E');
    exportItem.setAccelerator(KeyStroke.getKeyStroke("ctrl E"));
    exportItem.addActionListener(e -> exportData());

    JMenuItem exitItem = new JMenuItem("退出(X)");
    exitItem.setMnemonic('X');
    exitItem.setAccelerator(KeyStroke.getKeyStroke("ctrl Q"));
    exitItem.addActionListener(
        e -> {
          dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
        });

    fileMenu.add(exportItem);
    fileMenu.addSeparator();
    fileMenu.add(exitItem);

    // View menu
    JMenu viewMenu = new JMenu("视图(V)");
    viewMenu.setMnemonic('V');
    viewMenu.setFont(new Font("微软雅黑", Font.PLAIN, 12));

    JMenuItem refreshItem = new JMenuItem("刷新(R)");
    refreshItem.setMnemonic('R');
    refreshItem.setAccelerator(KeyStroke.getKeyStroke("F5"));
    refreshItem.addActionListener(e -> refreshCurrentView());

    viewMenu.add(refreshItem);

    // Help menu
    JMenu helpMenu = new JMenu("帮助(H)");
    helpMenu.setMnemonic('H');
    helpMenu.setFont(new Font("微软雅黑", Font.PLAIN, 12));

    JMenuItem aboutItem = new JMenuItem("关于(A)");
    aboutItem.setMnemonic('A');
    aboutItem.addActionListener(e -> showAboutDialog());

    helpMenu.add(aboutItem);

    // Add menus to menu bar
    menuBar.add(fileMenu);
    menuBar.add(viewMenu);
    menuBar.add(helpMenu);

    return menuBar;
  }

  /** Create status bar 创建状态栏 */
  private JPanel createStatusBar() {
    JPanel statusBar = new JPanel(new BorderLayout());
    statusBar.setBackground(new Color(240, 240, 240));
    statusBar.setBorder(BorderFactory.createLoweredBevelBorder());
    statusBar.setPreferredSize(new Dimension(0, 25));

    JLabel statusLabel = new JLabel("就绪");
    statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 11));
    statusLabel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));

    JLabel versionLabel = new JLabel("版本 1.0.0");
    versionLabel.setFont(new Font("微软雅黑", Font.PLAIN, 11));
    versionLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));

    statusBar.add(statusLabel, BorderLayout.WEST);
    statusBar.add(versionLabel, BorderLayout.EAST);

    // Store reference for updating
    statusBar.putClientProperty("statusLabel", statusLabel);

    return statusBar;
  }

  /** Create tab icon 创建选项卡图标 */
  private Icon createTabIcon(String emoji) {
    return new Icon() {
      @Override
      public void paintIcon(Component c, Graphics g, int x, int y) {
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        g2d.drawString(emoji, x, y + 12);
        g2d.dispose();
      }

      @Override
      public int getIconWidth() {
        return 16;
      }

      @Override
      public int getIconHeight() {
        return 16;
      }
    };
  }

  /** Create placeholder panel for unimplemented features 为未实现的功能创建占位面板 */
  private JPanel createPlaceholderPanel(String feature) {
    JPanel panel = new JPanel(new BorderLayout());
    panel.setBackground(Color.WHITE);

    JLabel label =
        new JLabel(
            "<html><center><h2>" + feature + "</h2><p>该功能正在开发中...</p></center></html>",
            JLabel.CENTER);
    label.setFont(new Font("微软雅黑", Font.PLAIN, 16));
    label.setForeground(new Color(128, 128, 128));

    panel.add(label, BorderLayout.CENTER);

    return panel;
  }

  /** Export data functionality 导出数据功能 */
  private void exportData() {
    JOptionPane.showMessageDialog(this, "数据导出功能正在开发中...", "功能提示", JOptionPane.INFORMATION_MESSAGE);
  }

  /** Refresh current view 刷新当前视图 */
  private void refreshCurrentView() {
    int selectedIndex = tabbedPane.getSelectedIndex();
    if (selectedIndex == 0 && todaySignUI != null) {
      // Refresh today's sign-in view
      Component[] components = todaySignUI.getComponents();
      // You can add specific refresh logic here
    }
    updateStatusBar("页面已刷新");
  }

  /** Show about dialog 显示关于对话框 */
  private void showAboutDialog() {
    String message =
        "<html><center>"
            + "<h2>学生签到管理系统</h2>"
            + "<p>版本: 1.0.0</p>"
            + "<p>开发技术: Java 21 + Swing</p>"
            + "<p>功能: 学生日常签到管理</p>"
            + "<br>"
            + "<p>© 2024 学生签到管理系统</p>"
            + "</center></html>";

    JOptionPane.showMessageDialog(this, message, "关于", JOptionPane.INFORMATION_MESSAGE);
  }

  /** Update status bar message 更新状态栏消息 */
  private void updateStatusBar(String message) {
    Component[] components = getContentPane().getComponents();
    for (Component comp : components) {
      if (comp instanceof JPanel) {
        JPanel panel = (JPanel) comp;
        Object statusLabel = panel.getClientProperty("statusLabel");
        if (statusLabel instanceof JLabel) {
          ((JLabel) statusLabel).setText(message);
          break;
        }
      }
    }
  }

  /** Show the main frame 显示主窗口 */
  public void showFrame() {
    SwingUtilities.invokeLater(
        () -> {
          setVisible(true);
          updateStatusBar("系统启动完成 - 当前页面: 今日签到");
        });
  }
}
